/**
 * 
 * @author Vanch
 * 
 */

;(function() {
	window.series_chart = function(container_id) {
		this.container_id = container_id;
		this.chart = null;
		this.currentSelect='';
		this.styleType='golden';//golden,white
	}

	//series_chart.prototype.init = function(styleType,xname,yname,xAxisData,yAxisData clickCallback) {
	//折线图初始化操作
	//xname:X轴单位，yname:Y轴单位，xAxisData:X轴初始化数据，yAxisData:Y轴初始化数据，
	series_chart.prototype.init = function(styleType, peroidType, clickCallback) {
		var self = this;
		self.styleType=styleType;
		//styleType='golden';
		
		var yname='百万';
		//默认X轴数据
		var xAxisData=self.getDefaultLabels(peroidType);
		//默认Y轴数据
		var yAxisData=self.getDefaultData(peroidType);
		
		self.callback=clickCallback;
		
		var domSeries = document.getElementById(self.container_id);
		var chartSeries = echarts.init(domSeries);
		self.chart = chartSeries;
		self.currentSelect='';
		
		self.zoom=(self.chart.getWidth()+self.chart.getHeight())/642;		
		self.pointSymbolSize=30*self.zoom;
		
		var nodata="y";
		var seriesType="line";

		//金色边折线图颜色列表
		var colorList=['#FCED1E','#FEFA8F','#FCED1E','#FCED1E','#FCED1E','#FCED1E'];
		if (styleType != "golden"){
			//白色边折线图颜色列表
			colorList = ['#999','#fff','#F1CFDD','#999','#fff','#F1CFDD'];
		}
		
		//过滤负值
		var iFilter=0;
		for(;iFilter<yAxisData.length;iFilter++){
			if(yAxisData[iFilter]<0){
				yAxisData[iFilter]=0;
			}
		}
		
		//没有数据，显示空表格
		if (nodata=="y"){
			seriesType="scatter";
		}
		
		//折线图参数配置
		optionSeries = {
                backgroundColor:'transparent',
				//设置边距
				grid:{
					right:'7%',
					left:'12%',
					top:'14%',
					bottom:'12%'
				},
                //数据提示框配置
                tooltip: {
    				show:false
    		    },
                //图例配置
                legend: {
    				show:false
    		    },
                //工具箱配置
                 toolbox: {
    		        show: false
    		    },
                calculable: true,  
                //X轴配置
                xAxis: [{
						type: 'category',  
						data: xAxisData,
						//name: xname,
						nameLocation: 'end',
						nameTextStyle:{
							fontSize:11*self.zoom
						},
						z:10000,
						splitLine: {
							show: true,
							interval:0,
							lineStyle: {
								color: colorList[0],
								type: 'dashed',
								width: 1*self.zoom,
								}
							},
						axisLabel: {
								margin:8*self.zoom,
								textStyle: {
									color: function (val) { //'#401B2D'
										return val == self.currentSelect ? '#FFFFFF' : colorList[1];
									},
									fontSize: 9*self.zoom
								}
							},
						axisLine: {
								lineStyle: {
									color: colorList[2],
									type: 'solid',
									width: 1*self.zoom,
								}
							}
                        }
                    ],
                //Y轴配置  
                yAxis: [{
						type: 'value', 
						name: yname,
						nameLocation: 'end',
						nameTextStyle:{
							fontSize:10*self.zoom
						},
						splitLine: {
							show: true,
							interval:0,
							lineStyle: {
								color: colorList[3],
								type: 'dashed',
								width: 1*self.zoom,
								}
							}, 
						axisLabel: {
								formatter: function (value, index) {
									return ""+value;
								},
								margin:8*self.zoom,
								textStyle: {
									color: colorList[4],
									fontSize: 12*self.zoom
								}
							},
						axisLine: {
								lineStyle: {
									color: colorList[5],
									type: 'solid',
									width: 1*self.zoom,
								}
							}
                        } 
                    ],  
                //图表Series数据序列配置
                series: [{
						name: '销售量',  
						type: seriesType,  
						smooth: false,
						symbol: 'circle',
						symbolSize: 0,
						hoverAnimation: false,
						label: {
								normal: {
									show: false,
									position: 'top'
								}
							},
						itemStyle: {
								normal: {
									color: '#F7B81F',
									borderWidth: 10
								}
							},
						lineStyle: {
								normal: {
									width: 2*self.zoom
								}
							},
						data: yAxisData  
					}]
            };
			
		//绘制折线图
		if (optionSeries && typeof optionSeries === "object") {
			chartSeries.setOption(optionSeries, true);
		}
	};
	
	//折线图刷新操作
	//xname:X轴单位，yname:Y轴单位，xAxisData:X轴初始化数据，yAxisData:Y轴初始化数据，
	series_chart.prototype.refresh=function(xAxisData, yAxisData, nodata, peroidType, defaultIndex){
		var self = this;
	
		if(peroidType=="月"){
			self.pointSymbolSize=25*self.zoom;
		}else{
			self.pointSymbolSize=30*self.zoom;
		}

		var yname='百万';
		var nodata = 'n';

		//默认X轴数据
		if(!xAxisData || xAxisData.length <= 1 || xAxisData == 0){
			//xAxisData=['A','B','C','D','E','F','G', "H", "I", "J"];
			//xAxisData=['1','2','3','4','5','6','7','8','9','10','11','12'];
			xAxisData=self.getDefaultLabels(peroidType);
			nodata="y";
		}
		//默认Y轴数据
		if(!yAxisData || yAxisData.length == 0 || yAxisData == 0){
			//yAxisData=['0','20','40','60','80','100','120', "140", "150"];
			//yAxisData=[0,0,0,0,0,0,0,0,0,0,0,0];
			yAxisData=self.getDefaultData(peroidType);
			nodata="y";
		}
		
		//年显示4位，其他周期x标签显示2位
		var i=0;
		if(peroidType != "年"){
			for(i=0;i<xAxisData.length;i++){
				xAxisData[i]=(""+xAxisData[i]).substring(xAxisData[i].length-2);
			}
		}
		
		//自动变换单位
		var scalar=1;
		var baseValue=1;
		
		yMaxData=0;
		yMinData=100000000000;
		for(i=0;i<yAxisData.length;i++){
			if(yAxisData[i]<0){
				yAxisData[i]=0;
			}
			if(yMaxData<yAxisData[i]){
				yMaxData=yAxisData[i];
			}
			if(yMinData>yAxisData[i]){
				yMinData=yAxisData[i];
			}
		}
		
		if(yMaxData<=0){
			yMaxData=1;
		}
		if(yMinData<=0){
			yMinData=1;
		}
		
		//计算单位数量级
		var scalarMax=Math.floor(Math.log(yMaxData)/Math.log(10))+1;
		var scalarMin=Math.floor(Math.log(yMinData)/Math.log(10))+1;
		
		if(yMinData<1){scalarMin=1}
		
		//scalar=scalarMax-scalarMin>1?Math.floor((scalarMax-scalarMin)/2):scalarMax;
		scalar=scalarMax-1;
		
		if(scalar>=8){
			var baseValue=100000000;
			var scalarLabel="亿";
		} else if(scalar>=7){
			var baseValue=10000000;
			var scalarLabel="千万";
		} else if(scalar>=6){
			var baseValue=1000000;
			var scalarLabel="百万";
		} else if(scalar>=4){
			var baseValue=10000;
			var scalarLabel="万";
		} else {
			var baseValue=1;
			var scalarLabel="元";
		}
		
		//变换单位
		if(scalar!=1){
			for(i=0;i<yAxisData.length;i++){
				yAxisData[i]=yAxisData[i]/baseValue;
			}
		}
		yname=scalarLabel;

		//保存图表数据
		self.xAxisData=xAxisData;
		self.yAxisData=yAxisData;
		self.nodata=nodata;

		var seriesType="line";
		
		if (nodata=="y"){
			seriesType="scatter";
			yname="";
		}
		
		//折线图刷新参数配置
		var optionSeries = {
			//X轴配置
			xAxis: {
				name: peroidType,
				nameLocation: 'end',
				data: xAxisData,
			},
			//Y轴配置
			yAxis: {
				name: yname,
				nameLocation: 'end',
			},
			//图表Series数据序列配置
			series: [{
				type: seriesType,  
				symbolSize: 0,
				hoverAnimation: false,
				itemStyle: {
						normal: {
							color: '#F7B81F',
							borderColor: '#F7B81F',
							shadowColor: '#F7B81F',
							borderWidth: 10
						},
						emphasis: {
							color: '#F7B81F',
							borderColor: '#F7B81F',
							shadowColor: '#F7B81F',
							borderWidth: 10
						}
					},
				lineStyle: {
								normal: {
									width: 2*self.zoom
								}
							},
				data: yAxisData
			}]
		};
		
		//刷新绘制折线图
		var chartSeries = self.chart;
		chartSeries.setOption(optionSeries);
		
		//带箭头的金色折线图默认选中最后一个数据
		if (nodata!="y"){
		//if (self.styleType == "golden"){
		
				//计算有效数据长度
				var len=xAxisData.length<yAxisData.length?xAxisData.length:yAxisData.length;
				
				//索引位置非法时，默认选中最后一列
				if (!(defaultIndex>=0 && defaultIndex <= len-1)){
					defaultIndex = len-1;
				}
				var selectedData=yAxisData[defaultIndex];
				var selectedLabel=xAxisData[defaultIndex];
				
				//转换坐标
				var ph = chartSeries.convertToPixel('grid', [selectedLabel, 10]);
				var pl = chartSeries.convertToPixel('grid', [selectedLabel, 0]);
				
				//计算位置
				var ypos=(10*13*self.zoom/(pl[1]-ph[1]));
				if (parseInt(selectedData) < ypos){
					ypos=parseInt(selectedData)+(10*12*self.zoom/(pl[1]-ph[1]));
				}
				
				var markDataList=[];
				var ii=0;
				for(;ii<len;ii++){
					markDataList.push({coord: [ii, yAxisData[ii]],symbol:'image://http://softtree.cn/allcharts/img/time_dot_out.png',symbolSize:self.pointSymbolSize,label: {normal: {show:false,}}});
				}
				
				//当前选中列
				self.currentSelect=selectedLabel;
				//markDataList.push({coord: [selectedLabel, ypos],symbol:'image://http://softtree.cn/allcharts/img/time_dot_clicked.png',symbolSize:self.pointSymbolSize,label: {normal: {show:false,}}});
				markDataList.push({coord: [selectedLabel, selectedData],symbol:'image://http://softtree.cn/allcharts/img/time_dot_clicked.png',symbolSize:self.pointSymbolSize,label: {normal: {show:false,}}});
				
				//对于金色图表用箭头标记默认选中列，同时触发刷新数据操作
				if (self.styleType == "golden"){
					markDataList.push({coord: [selectedLabel, ypos],symbol:'image://http://softtree.cn/allcharts/img/time_arrow.png',symbolSize:[30*self.zoom,75*self.zoom],label: {normal: {show:false,}}});
					//alert("刷新"+selectedLabel);
				}

				//设置选中参数
				optionMarkLast = {
					series: [{
						markPoint: {
								data: markDataList
							}
					}]
				};
				
				chartSeries.setOption(optionMarkLast);
		}
		
		//绘制点击区域
		if (nodata!="y"){
			var zr = chartSeries.getZr();
			var circleEl = new echarts.graphic.Circle({
				shape: {
					cx: 150,
					cy: 150,
					r: 10000
				},
				invisible: true,
				position: [150,150],
				onclick: echarts.util.curry(self.onPointClick, self),
				z: 20000
			});
			zr.add(circleEl);
		}
		
	};
	
	//响应点击折线图事件
series_chart.prototype.onPointClick = function(sc, evt) {
	//console.dir(evt);
	if (sc.nodata=="y"){
		return;
	}
	
	if(window.lock && window.lock==1){
		return;
	}
	
	var delay=1;
	window.lock=1;
	setTimeout("window.lock=0", delay*1000);

	//计算点击点
	var clickPoint = sc.chart.convertFromPixel('grid', [evt.offsetX,evt.offsetY]);
	var len=sc.xAxisData.length<sc.yAxisData.length?sc.xAxisData.length:sc.yAxisData.length;
	var markDataList=[];
	var i=0;
	for(;i<len;i++){
		markDataList.push({coord: [i, sc.yAxisData[i]],symbol:'image://http://softtree.cn/allcharts/img/time_dot_out.png',symbolSize:sc.pointSymbolSize,label: {normal: {show:false,}}});
	}
	
	//计算标记位置
	var ph = sc.chart.convertToPixel('grid', [0, 10]);
	var pl = sc.chart.convertToPixel('grid', [0, 0]);
	var ypos=(10*12*sc.zoom/(pl[1]-ph[1]));
	
	//白边框折线图只标记数据点
	var markData = [{coord: [clickPoint[0], sc.yAxisData[clickPoint[0]]]}];
	markDataList.push({coord: [clickPoint[0], sc.yAxisData[clickPoint[0]]],symbol:'image://http://softtree.cn/allcharts/img/time_dot_clicked.png',symbolSize:sc.pointSymbolSize,label: {normal: {show:false,}}});
	
	//白边框折线图不考虑当前选中的X值
	sc.currentSelect="";
	
	//对于金色图表用箭头选中列，同时触发刷新数据操作
	if (sc.styleType == "golden"){
		//金边框折线图需考虑当前选中的X值
		if (clickPoint[0]>=0 && clickPoint[0]< sc.xAxisData.length){
			sc.currentSelect=sc.xAxisData[clickPoint[0]];
		}
		
		//金边框折线图不仅标记数据点，还标记箭头
	    markDataList.push({coord: [clickPoint[0], ypos],symbol:'image://http://softtree.cn/allcharts/img/time_arrow.png',symbolSize:[30*sc.zoom,75*sc.zoom],label: {normal: {show:false,}}});
		
	}
	
	//设置标记参数
	var optionSeries = {
		series: [{
			markPoint: {
					data: markDataList
				}
		}]
	};
	
	sc.chart.setOption(optionSeries);
	//回调函数
	sc.callback(clickPoint[0]);
}

//获取日期名称
function getDay(t){
	var d = new Date();
	d.setDate(d.getDate()+t);
	
	var wd = d.getDate(); 
	if(wd < 10){ 
		wd = "0" + wd; 
	}
	
	return (wd); 
}

//获得缺省数值
series_chart.prototype.getDefaultData = function(peroid){

	//缺省年数据
	if(peroid == "年"){
		return [0,0,0,0,0,0];

	//缺省月数据
	} else if(peroid == "月"){
		return [0,0,0,0,0,0,0,0,0,0,0,0];

	//缺省日/周数据
	} else {
		return [0,0,0,0,0,0,0,0,0,0];
	}
}

//获得缺省标签
series_chart.prototype.getDefaultLabels = function(peroid){
	var xLabels=[];

	//缺省日标签
	if(peroid == "日"){
		var dd=(new Date()).getDate();
		if(dd<10){dd=10}
		//xLabels=[getDay(-9),getDay(-8),getDay(-7),getDay(-6),getDay(-5),getDay(-4),getDay(-3),getDay(-2),getDay(-1),getDay(0)];

		var idd=10;
		var lbd="";
		for (;idd>0;idd--){
			if((dd-idd+1) < 10){
				lbd="0"+(dd-idd+1);
			}else{
				lbd=""+(dd-idd+1);
			}
			xLabels.push(lbd);
		}

	//缺省周标签
	} else if(peroid == "周"){
		var d1 = new Date();
		var d2 = new Date();
		d2.setMonth(0);
		d2.setDate(1);
		var rq = d1-d2;
		var w1 = Math.ceil(rq/(24*60*60*1000));
		var w = Math.ceil(w1/7);
		if(w<10){w=10}
		
		var iw=10;
		var lbw="";
		for (;iw>0;iw--){
			if((w-iw+1) < 10){
				lbw="0"+(w-iw+1);
			}else{
				lbw=""+(w-iw+1);
			}
			xLabels.push(lbw);
		}
		
	//缺省月标签
	} else if(peroid == "月"){
		xLabels=['1','2','3','4','5','6','7','8','9','10','11','12'];

	//缺省年标签
	} else if(peroid == "年"){
		var y = (new Date()).getFullYear();
		var j=6;
		for (;j>0;j--){
			xLabels.push(y-j+1);
		}
		
	//缺省标签
	} else {
		xLabels = ['1','2','3','4','5','6','7','8','9','10'];
	}
	
	return xLabels;
}

})(Zepto);
